// 基于axios封装网络请求
import theAxios from 'axios'
import { Notify } from 'vant'
import router from '@/router'
import { getToken, removeTonken, setToken } from './token'
import { getNewTokenAPI } from '@/api'

const axios = theAxios.create({
  baseURL: 'http://toutiao.itheima.net',
  timeout: 200000
})

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  if (getToken()?.length > 0 && config.headers.Authourization === undefined) {
    config.headers.Authorization = `Bearer ${getToken()}`
  }
  return config
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error)
})

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  return response
}, async function (error) {
  // 对响应错误做点什么
  console.dir(error)
  if (error.response.status === 401) {
    removeTonken()
    const res = await getNewTokenAPI()
    console.log(res)
    setToken(res.data.data.token)
    // Notify({ type: 'warning', message: '身份已过期' })
    // router.replace('/login')
    error.config.headers.Authorization = `Bearer ${res.data.data.token}`
    return axios(error.config)
  } else if (error.config.method === 'put' && error.config.url === '/v1_0/authorizations' &&
  error.response.status === 500) {
    localStorage.clear()
    router.replace('/login')
    Notify({ type: 'warning', message: '请重新登录' })
  } return Promise.reject(error)
})

export default ({ url, method = 'GET', params = {}, data = {}, headers = {} }) => {
  return axios({
    url, method, params, data, headers
  })
}

export const firstActions = [
  { name: '不感兴趣' },
  { name: '反馈垃圾内容' }
]

export const secondActions = [
  {
    value: 0,
    name: '其它问题'
  },
  {
    value: 1,
    name: '标题夸张'
  },
  {
    value: 2,
    name: '低俗色情'
  },
  {
    value: 3,
    name: '错别字多'
  },
  {
    value: 4,
    name: '旧闻重复'
  },
  {
    value: 6,
    name: '内容不实'
  },
  {
    value: 8,
    name: '侵权'
  },
  {
    value: 5,
    name: '广告软文'
  },
  {
    value: 7,
    name: '涉嫌违法犯罪'
  }
]

// 有局限

// return new Promise ((resolve,reject)=>{
//     $.ajax({})
// })
